package com.coolgor.airvow.File;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class SimpleXML {
	String fileName = "";
	String fileStr = "";

	public SimpleXML(String fileName)
	{
		this.fileName = fileName;
		init();
	}
	
	public void init()
	{
		//获取当前操作系统路径的斜杠符号 若是win系统，则为“\” 若是linux系统，则为“/”
		String seperator = System.getProperty("file.separator");
		List<String> pathList = new ArrayList<String>();
		pathList.add("");
		//获取项目路径
		File f = new File("");
		String filePath = null;
		try {
			filePath = f.getCanonicalPath();
		} catch (IOException e) {
			e.printStackTrace();
		}
		filePath = filePath.replace("/", seperator) + seperator;
		pathList.add(filePath);
		pathList.add(filePath + "resources" + seperator);
		pathList.add(filePath + "configuration" + seperator);
		//获取classpath路径
		filePath = this.getClass().getResource("/").getPath().replace("/", seperator);
		pathList.add(filePath);
		pathList.add(filePath + "resources" + seperator);
		pathList.add(filePath + "configuration" + seperator);
		//循环检索文件是否存在
		File file ;
		for (int i=0;i<pathList.size();i++){
			file = new File(pathList.get(i) + fileName);
			if ((file.exists())) {
				this.fileStr = FileIO.read(pathList.get(i) + fileName);
				return;
			}
		}
		this.fileStr = "";
	}
	
	public String getString(String tag)
	{
		Vector list = getElementFromString(this.fileStr,tag);
		if (list.size()>0) return (String) list.get(0);
		else return null;
	}
	
	public Vector getElementFromString(String string, String tag)
	{
		Vector list = new Vector() ;
		Vector temp = new Vector() ;
		String s[] = string.split("<"+tag+">") ;
		for (int i=1;i<s.length;i++)
		{
			temp.add(s[i]);
		}
		for (int i=0;i<temp.size();i++)
		{
			list.add(((String) temp.get(i)).split("</"+tag+">")[0]);
		}
		if (list.size()>0) return list;
		else return null;
	}

}
